﻿using HospitalSalarySystem.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace HospitalSalarySystem.Forms
{
    public partial class EmployeeEditForm : Form
    {
        private readonly bool _editMode;

        public Employee Employee { get; private set; }

        // 学历选项列表
        private readonly List<string> _educationLevels = new List<string>
        {
            "博士", "硕士", "本科", "大专", "其他"
        };


        // 岗位等级选项列表
        private readonly List<string> _positionLevels = new List<string>
        {
            "专技三级","专技四级","专技五级","专技六级","专技七级","专技八级","专技九级","专技十级","专技十一级","专技十二级","专技十三级",
            "护理专技三级","护理专技四级","护理专技五级","护理专技六级","护理专技七级","护理专技八级","护理专技九级","护理专技十级","护理专技十一级","护理专技十二级","护理专技十三级",
            "七级职员","八级职员","九级职员","十级职员",
            "技术工三级","技术工四级","技术工五级","普通工"
        };

        /// <summary>
        /// 新增模式构造函数
        /// </summary>
        public EmployeeEditForm() : this(new Employee() { AppointmentDate = DateTime.Today, BirthDate = DateTime.Today, ConfirmationDate = DateTime.Today, EnrollmentDate = DateTime.Today, FirstHireDate = DateTime.Today, RenewalDate = DateTime.Today })
        {
            _editMode = false;
            Text = "新增员工信息";
        }

        /// <summary>
        /// 编辑模式构造函数
        /// </summary>
        public EmployeeEditForm(Employee employee)
        {
            InitializeComponent();
            Employee = employee ?? throw new ArgumentNullException(nameof(employee));
            _editMode = true;
            Text = "编辑员工信息";

            InitializeCustomComponents();
            BindData();
            SetupValidation();
        }

        /// <summary>
        /// 初始化自定义组件
        /// </summary>
        private void InitializeCustomComponents()
        {
            // 配置日期控件
            dtAppointmentDate.MaxDate = DateTime.Today;
            dtBirthDate.MaxDate = DateTime.Today;
            dtEnrollment.MaxDate = DateTime.Today;
            dtConfirmation.MaxDate = DateTime.Today;
            dtFirstHire.MaxDate = DateTime.Today;
            dtRenewal.MaxDate = DateTime.Today;

            // 配置下拉列表
            cbEducation.DataSource = new BindingSource(_educationLevels, null);
            cbPositionLevel.DataSource = new BindingSource(_positionLevels, null);

            // 配置工具提示
            toolTip.SetToolTip(cbPositionLevel, "请选择有效的岗位等级");
            toolTip.SetToolTip(dtAppointmentDate, "任职时间不能晚于当前日期");
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            txtName.Text = Employee.Name;
            dtAppointmentDate.Value = (Employee.AppointmentDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.AppointmentDate);
            dtBirthDate.Value = (Employee.BirthDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.BirthDate);
            dtEnrollment.Value = (Employee.EnrollmentDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.EnrollmentDate);
            cbEducation.SelectedItem = Employee.Education;
            txtQualification.Text = Employee.Qualification;
            dtConfirmation.Value = (Employee.ConfirmationDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.ConfirmationDate);
            txtCurrentTitle.Text = Employee.CurrentTitle;
            dtFirstHire.Value = (Employee.FirstHireDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.FirstHireDate);
            dtRenewal.Value = (Employee.RenewalDate.Year == 1 ? dtAppointmentDate.MinDate : Employee.RenewalDate);
            cbPositionLevel.SelectedItem = Employee.PositionLevel;
            chkIsFormal.Checked = Employee.IsNurse;
            chkIsBiannei.Checked = Employee.IsBiannei;
            txtRemarks.Text = Employee.Remarks;
        }

        /// <summary>
        /// 设置验证规则
        /// </summary>
        private void SetupValidation()
        {
            // 配置自动验证
            txtName.Validating += (s, e) => ValidateRequired(txtName, "姓名");
            cbEducation.Validating += (s, e) => ValidateRequired(cbEducation, "学历");
            cbPositionLevel.Validating += (s, e) => ValidateRequired(cbPositionLevel, "岗位等级");
            dtAppointmentDate.Validating += (s, e) => ValidateDateOrder(dtAppointmentDate, dtBirthDate, "任职时间不能早于出生日期");
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateChildren(ValidationConstraints.Enabled))
            {
                MessageBox.Show("请修正表单中的错误后再保存", "验证错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            UpdateEmployee();
            DialogResult = DialogResult.OK;
            Close();
        }

        /// <summary>
        /// 更新员工对象
        /// </summary>
        private void UpdateEmployee()
        {
            Employee.Name = txtName.Text.Trim();
            Employee.AppointmentDate = dtAppointmentDate.Value;
            Employee.BirthDate = dtBirthDate.Value;
            Employee.EnrollmentDate = dtEnrollment.Value;
            Employee.Education = cbEducation.SelectedItem?.ToString();
            Employee.Qualification = txtQualification.Text.Trim();
            Employee.ConfirmationDate = dtConfirmation.Value;
            Employee.CurrentTitle = txtCurrentTitle.Text.Trim();
            Employee.FirstHireDate = dtFirstHire.Value;
            Employee.RenewalDate = dtRenewal.Value;
            Employee.PositionLevel = cbPositionLevel.SelectedItem?.ToString();
            Employee.IsNurse = chkIsFormal.Checked;
            Employee.Remarks = txtRemarks.Text.Trim();
            Employee.IsBiannei = chkIsBiannei.Checked;
        }

        #region 验证方法
        private bool ValidateRequired(Control control, string fieldName)
        {
            var isValid = !string.IsNullOrWhiteSpace(control.Text);
            errorProvider.SetError(control, isValid ? "" : $"{fieldName}不能为空");
            return isValid;
        }

        private bool ValidateDateOrder(DateTimePicker earlierDate, DateTimePicker laterDate, string errorMessage)
        {
            var isValid = earlierDate.Value <= laterDate.Value;
            errorProvider.SetError(earlierDate, isValid ? "" : errorMessage);
            return isValid;
        }

        private bool ValidateListSelection(ComboBox comboBox, string fieldName)
        {
            var isValid = comboBox.SelectedItem != null;
            errorProvider.SetError(comboBox, isValid ? "" : $"{fieldName}必须选择有效值");
            return isValid;
        }
        #endregion

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (_editMode && HasChanges())
            {
                var result = MessageBox.Show("是否放弃当前修改？", "确认取消",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes) return;
            }

            DialogResult = DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// 检查数据是否修改
        /// </summary>
        private bool HasChanges()
        {
            return !Employee.Equals(new Employee
            {
                Name = txtName.Text.Trim(),
                AppointmentDate = dtAppointmentDate.Value,
                BirthDate = dtBirthDate.Value,
                EnrollmentDate = dtEnrollment.Value,
                Education = cbEducation.SelectedItem?.ToString(),
                Qualification = txtQualification.Text.Trim(),
                ConfirmationDate = dtConfirmation.Value,
                CurrentTitle = txtCurrentTitle.Text.Trim(),
                FirstHireDate = dtFirstHire.Value,
                RenewalDate = dtRenewal.Value,
                PositionLevel = cbPositionLevel.SelectedItem?.ToString(),
                IsNurse = chkIsFormal.Checked,
                Remarks = txtRemarks.Text.Trim()
            });
        }

        /// <summary>
        /// 窗口关闭前验证
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (DialogResult != DialogResult.OK && HasChanges() && !closeform)
            {
                var result = MessageBox.Show("当前修改尚未保存，确定要退出吗？", "未保存修改",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                e.Cancel = (result == DialogResult.No);
            }
            base.OnFormClosing(e);
        }

        bool closeform = false;
        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            closeform = true;
            this.Close();
        }


    }
}